﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sustainalytics.Synchronization.Validation.Validators;

namespace Sustainalytics.Synchronization.Validation.Log
{
    public class SyncSummaryLogClient : ILogClient
    {
        private readonly Action<string> syncLogging;

        public SyncSummaryLogClient(Action<string> syncLogging)
        {
            this.syncLogging = syncLogging;
        }

        public void WriteAsync(IEnumerable<ValidationFailure> summary)
        {
            var groupedItems = from i in summary
                               group i by i.Severity
                               into newGroup1
                               from newGroup2 in
                                   from y in newGroup1
                                   group y by y.Code
                                   into g select new { g.Key, Count = g.Count() }
                               group newGroup2 by newGroup1.Key
                               into result
                               select
                                   new
                                       {
                                           Severity = result.Key, 
                                           RuleAgg =
                                   result.Select(x => new { RuleName = x.Key, BrokenRulesCount = x.Count })
                                       };

            var sb = new StringBuilder();

            foreach (var data in groupedItems)
            {
                foreach (var ruleData in data.RuleAgg)
                {
                    sb.AppendLine(
                        string.Format(
                            "{0} -{1} broken rules {2}", 
                            data.Severity, 
                            ruleData.RuleName, 
                            ruleData.BrokenRulesCount));
                }
            }

            syncLogging.Invoke(sb.ToString());
        }
    }
}